package ${appProperty.basePackage}.config;

import com.taobao.tddl.client.jdbc.TDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
* @author ${appProperty.author}
* @version V1.0
* <p>Description: tddl 配置</p>
* @date ${appProperty.dateTime}
*/
@Slf4j
@Configuration
@MapperScan(value = "${appProperty.basePackage}.dao", sqlSessionFactoryRef = "tddlSqlSessionFactory")
public class TddlConfig {

    @Primary
    @Bean(name = "tddlDataSource")
    public DataSource createTddlDataSource(@Value("${r'$'}{spring.tddl.app}") String app
    , @Value("${r'$'}{spring.tddl.sharding}") boolean sharding
    , @Value("${r'$'}{spring.tddl.rule-file-path}") String ruleFile
    , @Value("${r'$'}{spring.tddl.unitName}") String unitName) {

        TDataSource tds = new TDataSource();
        tds.setAppName(app);
        tds.setDynamicRule(sharding);
        tds.setRuleFile(ruleFile);
        log.info("unitName: " + unitName);
        if (StringUtils.isNotBlank(unitName)) {
            tds.setUnitName(unitName);
        }
        tds.init();
        return tds;
    }

    @Bean(name = "tddlSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("tddlDataSource") DataSource tddlDataSource) throws Exception {

        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setCacheEnabled(false);
        configuration.setMapUnderscoreToCamelCase(true);

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources("classpath*:mapper/*.xml");
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(tddlDataSource);
        sqlSessionFactory.setMapperLocations(resources);

        return sqlSessionFactory.getObject();
    }

    @Bean("tddlSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("tddlSqlSessionFactory")
        SqlSessionFactory tddlSqlSessionFactory) {
        return new SqlSessionTemplate(tddlSqlSessionFactory);
    }
}
